package com.android.meige.fragment.member;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.meige.R;
import com.android.meige.fragment.BaseLazyFragment;
import com.android.meige.model.member.ScoreDetailList;
import com.android.meige.model.member.ScoreDetailListCallback;
import com.android.meige.utils.ConstantsUrl;
import com.android.meige.utils.HttpUtils;
import com.android.meige.utils.MyLog;
import com.android.meige.utils.ObjectUtils;
import com.android.meige.view.recycleview.CustomLoadMoreView;
import com.android.meige.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * 积分明细列表
 */
public class Fragment_Mine_Score_Detail extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener, View.OnClickListener {

    @BindView(R.id.top)
    ImageView top;
    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.detail_rate_tip)
    RelativeLayout detailRateTip;
    @BindView(R.id.score_left)
    TextView scoreLeft;
    @BindView(R.id.tv_score_type)
    TextView scoreType;

    private FragmentActivity mcontext;
    private View view;
    private String type = "";
    private boolean networkConnected;
    private int page = 1;
    private ScoreDetailAdapt adapter;
    PopupWindow mPopWindow;
    private TextView typeAll;
    private TextView typeOther;
    private TextView typeSign;
    private TextView typeRegister;
    private TextView typeTuan;
    private TextView typeConversion;

    public Fragment_Mine_Score_Detail() {


    }

    public static Fragment_Mine_Score_Detail newInstance() {
        Fragment_Mine_Score_Detail fragment = new Fragment_Mine_Score_Detail();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private void initRecycle() {
        adapter = new ScoreDetailAdapt(R.layout.item_score_detail_list, null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop(top, 0);
    }

    @Override
    protected void onInvisible() {
    }


    @Override
    protected void initData() {
        initPopupWindow();
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            getScoreData(page, type);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_mine_score_detail, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        initRecycle();
        mRecyclerView.setBackgroundColor(Color.WHITE);
        noData.setVisibility(View.GONE);
        return view;
    }

    private void ReFreshData() {
        mRefreshLayout.setColorSchemeResources(R.color.app_title);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                if (networkConnected) {
                    page = 1;
                    getScoreData(page, type);
                } else {
                    ObjectUtils.toast(mcontext, "网络连接出现异常");
                    mRefreshLayout.setRefreshing(false);
                }
            }
        });
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        getScoreData(page, type);
    }

    private void getScoreData(final int page, String type) {
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.SCORE_DETAIL;
            MyLog.e("地址", address);
            HashMap<String, String> map = new HashMap<>();
            map.put("page", page + "");
            if (!type.equals("")) {
                map.put("type", type + "");
            }
            HttpUtils.get(address, map, dataCallback);
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    ScoreDetailListCallback dataCallback = new ScoreDetailListCallback() {

        @Override
        public void onError(Call call, Exception e, int id) {
            mRefreshLayout.setRefreshing(false);
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
        }

        @Override
        public void onResponse(ScoreDetailList response, int id) {
            mRefreshLayout.setRefreshing(false);
            if (response == null) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                return;
            }
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
            if (response.getCode() == 0 && response.getData() != null) {
                ScoreDetailList.DataBean data = response.getData();
                ArrayList<ScoreDetailList.DataBean.ListBean> listData = new ArrayList<>();
                ScoreDetailList.DataBean.ScoreBean scoreBean = data.getScore();
                if(scoreBean!=null){
                    scoreLeft.setText(scoreBean.getTotal_left());
                }
                if (!ObjectUtils.listHasData(data.getList())) {
                    if (page == 1) {
                        detailRateTip.setVisibility(View.VISIBLE);
                    } else {
                        adapter.loadMoreEnd();
                    }
                    return;
                }
                listData.addAll(data.getList());
                if (page == 1) {
                    adapter.setNewData(listData);
                } else {
                    adapter.addData(listData);
                    adapter.loadMoreComplete();
                }
                noData.setVisibility(View.GONE);
                detailRateTip.setVisibility(View.GONE);
            } else {
                if (page == 1) {
                    noData.setVisibility(View.VISIBLE);
                } else {
                    adapter.loadMoreFail();
                    ObjectUtils.toast(mcontext, response.getMsg());
                }
            }
        }
    };

    private class ScoreDetailAdapt extends BaseQuickAdapter<ScoreDetailList.DataBean.ListBean, BaseViewHolder> {

        public ScoreDetailAdapt(int layoutResId, List<ScoreDetailList.DataBean.ListBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder holder, ScoreDetailList.DataBean.ListBean data) {
            holder.setText(R.id.item_score_detail_remark, data.getRemark());
            String strTime = ObjectUtils.getStrTime(data.getC_time(), "yyyy-MM-dd HH:mm:ss");
            holder.setText(R.id.item_score_detail_time, strTime);
            holder.setText(R.id.item_score_detail_type, data.getScore_type());
        }
    }

    @OnClick({R.id.tv_score_type, R.id.click_resetnetwork_refresh})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_score_type:
                showPop();
                break;
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
                getScoreData(page, type);
                break;
            case R.id.type_all:
                setPop(typeAll);
                type = "";
                page = 1;
                getScoreData(page, type);
                scoreType.setText("全部类型");
                break;
            case R.id.type_other:
                setPop(typeOther);
                type = "0";
                page = 1;
                getScoreData(page, type);
                scoreType.setText("其他类型");
                break;
            case R.id.type_sign:
                setPop(typeSign);
                type = "1";
                page = 1;
                getScoreData(page, type);
                scoreType.setText("签到积分");
                break;
            case R.id.type_register:
                setPop(typeRegister);
                type = "2";
                page = 1;
                getScoreData(page, type);
                scoreType.setText("注册积分");
                break;
            case R.id.type_tuan:
                setPop(typeTuan);
                type = "5";
                page = 1;
                getScoreData(page, type);
                scoreType.setText("团购积分");
                break;
            case R.id.type_conversion:
                setPop(typeConversion);
                type = "6";
                page = 1;
                getScoreData(page, type);
                scoreType.setText("积分兑换");
                break;
        }
    }

    private void setPop(TextView tv) {
        intPopText();
        tv.setBackgroundColor(Color.RED);
        tv.setTextColor(Color.WHITE);
        showPop();
    }

    private void showPop() {
        if (mPopWindow == null) return;
        if (mPopWindow.isShowing()) {
            mPopWindow.dismiss();
        } else {
            mPopWindow.showAsDropDown(scoreType);
        }
    }

    @NonNull
    private void initPopupWindow() {
        View contentView = LayoutInflater.from(mcontext).inflate(R.layout.popuwindow_score_type, null);
        mPopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        mPopWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setFocusable(true);
        typeAll = (TextView) contentView.findViewById(R.id.type_all);
        typeOther = (TextView) contentView.findViewById(R.id.type_other);
        typeSign = (TextView) contentView.findViewById(R.id.type_sign);
        typeRegister = (TextView) contentView.findViewById(R.id.type_register);
        typeTuan = (TextView) contentView.findViewById(R.id.type_tuan);
        typeConversion = (TextView) contentView.findViewById(R.id.type_conversion);
        typeAll.setOnClickListener(this);
        typeOther.setOnClickListener(this);
        typeSign.setOnClickListener(this);
        typeRegister.setOnClickListener(this);
        typeTuan.setOnClickListener(this);
        typeConversion.setOnClickListener(this);
    }

    private void intPopText() {
        typeAll.setBackgroundColor(Color.TRANSPARENT);
        typeOther.setBackgroundColor(Color.TRANSPARENT);
        typeSign.setBackgroundColor(Color.TRANSPARENT);
        typeRegister.setBackgroundColor(Color.TRANSPARENT);
        typeTuan.setBackgroundColor(Color.TRANSPARENT);
        typeConversion.setBackgroundColor(Color.TRANSPARENT);

        typeAll.setTextColor(Color.BLACK);
        typeOther.setTextColor(Color.BLACK);
        typeSign.setTextColor(Color.BLACK);
        typeRegister.setTextColor(Color.BLACK);
        typeTuan.setTextColor(Color.BLACK);
        typeConversion.setTextColor(Color.BLACK);
    }
}
